package com.yitong.equipment.ui.home

import android.content.res.Configuration
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import com.aliyun.player.aliyunplayerbase.util.ScreenUtils
import com.aliyun.player.source.UrlSource
import com.aliyun.player.theme.Theme
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.entity.node.BaseNode
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ImmersionBar
import com.yitong.equipment.R
import com.yitong.equipment.base.BaseActivity
import com.yitong.equipment.constant.EventIds
import com.yitong.equipment.databinding.ActivityCourseDetailBinding
import com.yitong.equipment.entity.other.Event
import com.yitong.equipment.ext.init
import com.yitong.equipment.ui.adapter.CourseDetailAdapter
import com.yitong.equipment.ui.adapter.courseprovider.FirstData
import com.yitong.equipment.ui.adapter.courseprovider.SecondData
import com.yitong.equipment.ui.viewmodel.CourseDetailViewModel
import java.util.ArrayList


class CourseDetailActivity : BaseActivity<CourseDetailViewModel, ActivityCourseDetailBinding>() {
    private val courseDetailAdapter: CourseDetailAdapter by lazy { CourseDetailAdapter() }
    private val titles = arrayOf("课程", "介绍", "评价")

    private var bannerHeight = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_course_detail)
        initView()
    }


    private fun initView() {
        ImmersionBar.setTitleBar(this, bindingView.courseDetailTopLayout.toolbar)
        val bannerParams: ViewGroup.LayoutParams = bindingView.aliyunPlayer.layoutParams
        val titleBarParams: ViewGroup.LayoutParams = bindingView.courseDetailTopLayout.toolbar.layoutParams
        bannerHeight = bannerParams.height - titleBarParams.height - ImmersionBar.getStatusBarHeight(this)
        bindingView.nestedScrollView.run {
            setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
                var alpha = 0
                var scale = 0f
                override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                    if (scrollY <= bannerHeight) {
                        scale = scrollY.toFloat() / bannerHeight
                        alpha = (255 * scale).toInt()
                        bindingView.courseDetailTopLayout.toolbar.setBackgroundColor(setColor(alpha))
                        bindingView.courseDetailTopLayout.tabLayout.visibility = View.GONE
                    } else {
                        if (alpha < 255) {
                            alpha = 255
                            bindingView.courseDetailTopLayout.toolbar.setBackgroundColor(setColor(alpha))
                            bindingView.courseDetailTopLayout.tabLayout.visibility = View.VISIBLE
                        }
                    }

                    var height1 = bindingView.layout1.measuredHeight
                    var height2 = bindingView.layout2.measuredHeight
                    var height3 = bindingView.layout3.measuredHeight
                    if (scrollY <= height1 + bannerHeight) {
                        if (bindingView.courseDetailTopLayout.tabLayout.selectedTabPosition == 0) {
                            return
                        }
                        bindingView.courseDetailTopLayout.tabLayout.getTabAt(0)?.select()
                    } else if (scrollY >= height1 + bannerHeight && scrollY <= height1 + height2 + bannerHeight) {
                        if (bindingView.courseDetailTopLayout.tabLayout.selectedTabPosition == 1) {
                            return
                        }
                        bindingView.courseDetailTopLayout.tabLayout.getTabAt(1)?.select()
                    } else if (scrollY >= height1 + height2 + bannerHeight && scrollY <= height1 + height2 + height3 + bannerHeight) {
                        if (bindingView.courseDetailTopLayout.tabLayout.selectedTabPosition == 2) {
                            return
                        }
                        bindingView.courseDetailTopLayout.tabLayout.getTabAt(2)?.select()
                    }
                }
            })
        }


        bindingView.courseDetailTopLayout.imgBack.setOnClickListener {
            finish()
        }


        for (index in titles.indices) {
            bindingView.courseDetailTopLayout.tabLayout.addTab(bindingView.courseDetailTopLayout.tabLayout.newTab().setText(titles[index]))
        }


        bindingView.courseDetailTopLayout.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {

//                if (tab?.position==0) {
//                    bindingView.nestedScrollView.smoothScrollTo(0,bannerHeight)
//                }else if (tab?.position==1) {
//                    bindingView.nestedScrollView.smoothScrollTo(0,bindingView.layout1.measuredHeight+bannerHeight)
//                }else if (tab?.position==2) {
//                    bindingView.nestedScrollView.smoothScrollTo(0,bindingView.layout1.measuredHeight+bindingView.layout2.measuredHeight+bannerHeight)
//                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })
        bindingView.recycleView.init(LinearLayoutManager(this), courseDetailAdapter, false)


        courseDetailAdapter.setList(getEntity())



        //todo  测试
        bindingView.aliyunPlayer.run {
            keepScreenOn = true
            setTheme(Theme.Blue)

            var urlSource = UrlSource()
            urlSource.uri = "https://alivc-demo-cms.alicdn.com/video/videoAD.mp4"
            setLocalSource(urlSource)
            setCoverUri("https://m.360buyimg.com/mobilecms/s700x280_jfs/t1/181068/13/16622/771845/6102a71aE15dbe36e/c7f4953bb30e1efe.png!cr_1053x420_4_0!q70.jpg")
            setAutoPlay(false)
            /**
             * 屏幕方向改变
             *
             * @param from        从横屏切换为竖屏, 从竖屏切换为横屏
             * @param currentMode 当前屏幕类型
             */
            setOrientationChangeListener { from, currentMode ->
                LogUtils.dTag("setOrientationChangeListener", "from=$from")
                LogUtils.dTag("setOrientationChangeListener", "currentMode=$currentMode")

            }
        }

    }


   override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        updatePlayerViewMode()
    }

    private fun updatePlayerViewMode() {
        if (bindingView.aliyunPlayer != null) {
            val orientation = resources.configuration.orientation

            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                this.window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                bindingView.aliyunPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE)

                //设置view的布局，宽高之类
                val aliVcVideoViewLayoutParams = bindingView.aliyunPlayer.getLayoutParams() as RelativeLayout.LayoutParams
                aliVcVideoViewLayoutParams.height = (ScreenUtils.getWidth(this) * 9.0f / 16).toInt()
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //转到横屏了。
                //隐藏状态栏
                if (!isStrangePhone()) {
                    this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
                    bindingView.aliyunPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
                }
                //设置view的布局，宽高
                val aliVcVideoViewLayoutParams = bindingView.aliyunPlayer.getLayoutParams() as RelativeLayout.LayoutParams
                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            }
        }
    }

    private fun getEntity(): List<BaseNode>? {
        val list: MutableList<BaseNode> = ArrayList()
        for (i in 0..7) {
            val secondNodeList: MutableList<BaseNode> = ArrayList()
            for (n in 0..5) {
                val seNode = SecondData("我是视频$n", "15分钟")
                secondNodeList.add(seNode)
            }
            val entity = FirstData(secondNodeList, "我是课程$i")

            // 模拟 默认第0个是展开的
            entity.isExpanded = (i == 0)
            list.add(entity)
        }
        return list
    }


    fun setColor(alpha: Int): Int {
        return Color.argb(alpha, 255, 255, 255)
    }


    override fun receiveEvent(event: Event<Any>) {
        if (event.code == EventIds.UPDATE_RECYCLER_HEIGHT) {
            if (bindingView.recycleView.height > 0) {
                val params: ViewGroup.LayoutParams = bindingView.recycleView.layoutParams
                params.height = ViewGroup.LayoutParams.WRAP_CONTENT
                bindingView.recycleView.layoutParams = params
            }
        }

    }

    override fun isRegisterEventBus(): Boolean {
        return true
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    override fun isImmersionBarEnabled(): Boolean {
        return true
    }

    private fun isStrangePhone(): Boolean {
        return "mx5".equals(Build.DEVICE, ignoreCase = true) || "Redmi Note2".equals(Build.DEVICE, ignoreCase = true) || "Z00A_1".equals(Build.DEVICE,
            ignoreCase = true) || "hwH60-L02".equals(Build.DEVICE, ignoreCase = true) || "hermes".equals(Build.DEVICE, ignoreCase = true) || "V4".equals(Build.DEVICE,
            ignoreCase = true) && "Meitu".equals(Build.MANUFACTURER, ignoreCase = true) || "m1metal".equals(Build.DEVICE, ignoreCase = true) && "Meizu".equals(Build.MANUFACTURER, ignoreCase = true)
    }
}